package com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.ydkj.a37e_mall.Classes.Applicatiom.MyApplication;
import com.ydkj.a37e_mall.Classes.Model.Request.AddressListReq;
import com.ydkj.a37e_mall.Classes.Model.Request.DeleteAddressReq;
import com.ydkj.a37e_mall.Classes.Model.Response.AddressListResp;
import com.ydkj.a37e_mall.Classes.Model.Response.DebitcardResp;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_get;
import com.ydkj.a37e_mall.Resource.Utils.CommonUtil;
import com.ydkj.a37e_mall.Resource.Utils.Const;
import com.ydkj.a37e_mall.Resource.Utils.GsonImpl;
import com.ydkj.a37e_mall.Resource.Utils.Rsa;
import com.ydkj.a37e_mall.Resource.Utils.SharedPreferencesUtil;
import com.ydkj.a37e_mall.Resource.View.CustomProgressDialog;
import com.ydkj.a37e_mall.Resource.View.StatusBarUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

import static android.R.id.edit;

/**
 * Created by Administrator on 2017/1/18.
 * 管理地址
 */

public class ManageAddressActivity extends BaseActivity implements View.OnClickListener {
    private Activity mActivity;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private MyApplication myApplication;
    private AddressListAdapter addressListAdapter;
    private List<AddressListResp.ResultEntity.DataEntity> addressInfoList;

    private ImageView img_back;
    private ListView lv_address;
    private TextView tv_edit, tv_addNewAdreess, tv_delete;
    private String secret;
    private boolean is_edit = false;
    private List<Integer> idList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.manage_address);
        mActivity = this;
        init();
        GetAddressList();
//        initWindow();
    }

    private void initWindow() {
        StatusBarUtil.setColor(mActivity, getResources().getColor(R.color.A000000), 0);

    }

    private void init() {
        myApplication = MyApplication.getInstance();
        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(mActivity);
        tv_edit = (TextView) mActivity.findViewById(R.id.tv_edit);
        tv_addNewAdreess = (TextView) mActivity.findViewById(R.id.tv_addNewAdreess);
        tv_delete = (TextView) mActivity.findViewById(R.id.tv_delete);
        img_back = (ImageView) mActivity.findViewById(R.id.img_back);
        lv_address = (ListView) mActivity.findViewById(R.id.lv_address);

        idList = new ArrayList<Integer>();
        addressInfoList = new ArrayList<AddressListResp.ResultEntity.DataEntity>();
        addressListAdapter = new AddressListAdapter(addressInfoList);
        lv_address.setAdapter(addressListAdapter);

        img_back.setOnClickListener(this);
        tv_edit.setOnClickListener(this);
        tv_addNewAdreess.setOnClickListener(this);
        tv_delete.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.img_back://返回
                intent = new Intent();
                setResult(Activity.RESULT_OK, intent);
                finish();
                break;
            case R.id.tv_edit://编辑
                if (is_edit == false) {
                    tv_edit.setText("完成");
                    tv_addNewAdreess.setVisibility(View.GONE);
                    tv_delete.setVisibility(View.VISIBLE);
                    is_edit = true;
                } else {
                    tv_edit.setText("编辑");
                    tv_addNewAdreess.setVisibility(View.VISIBLE);
                    tv_delete.setVisibility(View.GONE);
                    is_edit = false;
                }
                addressListAdapter.notifyDataSetChanged();
                break;
            case R.id.tv_addNewAdreess://添加新地址
                myApplication.setName1("");
                myApplication.setMobile1("");
                myApplication.setZip_code1("");
                myApplication.setAddress1("");
                myApplication.setProvince1("");
                myApplication.setCity1("");
                myApplication.setArea1("");
                myApplication.setLocation1("");
                myApplication.setDetail1("");
                myApplication.setIs_default1("");
                intent = new Intent(mActivity, AddNewAddress.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.tv_delete://删除
                DeleteReceiptAddress();
                break;
        }
    }

    private class AddressListAdapter extends BaseAdapter {
        private List<AddressListResp.ResultEntity.DataEntity> addressInfoList;

        private AddressListAdapter(List<AddressListResp.ResultEntity.DataEntity> infos) {
            if (infos == null) {
                infos = new ArrayList<AddressListResp.ResultEntity.DataEntity>();
            }
            addressInfoList = infos;
        }

        @Override
        public int getCount() {
            return addressInfoList.size();
        }

        /**
         * 获得某一位置的数据
         */
        @Override
        public AddressListResp.ResultEntity.DataEntity getItem(int position) {
            return addressInfoList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder vh = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.address_listitem, null);
                vh = new ViewHolder();
                vh.ly_confirmation_address = (LinearLayout) convertView.findViewById(R.id.ly_confirmation_address);
//                vh.img_choose = (ImageView) convertView.findViewById(R.id.img_choose);
                vh.cb_choose = (ImageView) convertView.findViewById(R.id.cb_choose);
                vh.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
                vh.tv_phoneNumber = (TextView) convertView.findViewById(R.id.tv_phoneNumber);
                vh.tv_address = (TextView) convertView.findViewById(R.id.tv_address);
                vh.tv_default = (TextView) convertView.findViewById(R.id.tv_default);
            } else {
                vh = (ViewHolder) convertView.getTag();
            }
            convertView.setTag(vh);
            convertView.setClickable(true);


            vh.tv_name.setText(getItem(position).getName());
            vh.tv_phoneNumber.setText(getItem(position).getMobile());
            vh.tv_address.setText(getItem(position).getDetail());

            //编辑
            if (is_edit == true) {
                vh.cb_choose.setVisibility(View.VISIBLE);
                tv_edit.setText("完成");

            } else {
                vh.cb_choose.setVisibility(View.GONE);
                tv_edit.setText("编辑");
            }

            //设置默认地址
            if (getItem(position).getIs_default() == 1) {
                vh.ly_confirmation_address.setBackgroundColor(getResources().getColor(R.color.f1f1f1));
                vh.tv_name.setTextColor(getResources().getColor(R.color.e50011));
                vh.tv_phoneNumber.setTextColor(getResources().getColor(R.color.e50011));
                vh.tv_address.setTextColor(getResources().getColor(R.color.e50011));
                vh.tv_address.setTextSize(14);
                vh.tv_default.setVisibility(View.VISIBLE);
            } else {
                vh.ly_confirmation_address.setBackgroundColor(getResources().getColor(R.color.ffffff));
                vh.tv_name.setTextColor(getResources().getColor(R.color.A333333));
                vh.tv_phoneNumber.setTextColor(getResources().getColor(R.color.A333333));
                vh.tv_address.setTextColor(getResources().getColor(R.color.A333333));
                vh.tv_address.setTextSize(12);
                vh.tv_default.setVisibility(View.GONE);
            }


            vh.ly_confirmation_address.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (is_edit == true) {
                        Log.e("ssss", "1111");
                        AddressListResp.ResultEntity.DataEntity info = addressInfoList.get(position);
                        for (AddressListResp.ResultEntity.DataEntity infos : addressInfoList) {
                            if (infos.getAddress().equals(info.getAddress())) {
                                infos.setIs_check(true);
                            } else {
                                infos.setIs_check(false);
                            }
                            addressListAdapter.notifyDataSetChanged();
                        }
                    }
                }
            });
            AddressListResp.ResultEntity.DataEntity info = addressInfoList.get(position);
            if (info.is_check()) {
//                vh.img_bankcard_list_select.setVisibility(View.VISIBLE);

                vh.cb_choose.setBackground(getResources().getDrawable(R.mipmap.choose_red));

            } else {
                vh.cb_choose.setBackground(getResources().getDrawable(R.mipmap.choose_default));

            }


            //点击convertView
            final ViewHolder finalVh = vh;
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    //如果在编辑状态，点击convertView 变为选择
                    if (is_edit == true) {
                        AddressListResp.ResultEntity.DataEntity info = addressInfoList.get(position);
                        for (AddressListResp.ResultEntity.DataEntity infos : addressInfoList) {
                            if (infos.getAddress().equals(info.getAddress())) {
                                infos.setIs_check(true);
                            } else {
                                infos.setIs_check(false);
                            }
                            addressListAdapter.notifyDataSetChanged();
                        }
                        addressListAdapter.notifyDataSetChanged();
                    } else {
                        //否则就跳转到地址编辑界面
                        Intent intent = new Intent(mActivity, EditAddress.class);
                        Log.e("url", "id==" + getItem(position).getId());
                        myApplication.setId(getItem(position).getId());
                        myApplication.setName(getItem(position).getName());
                        myApplication.setAddress(getItem(position).getAddress());
                        myApplication.setProvince(getItem(position).getProvince());
                        myApplication.setProvince_id(getItem(position).getProvince_id() + "");
                        myApplication.setCity(getItem(position).getCity());
                        myApplication.setCity_id(getItem(position).getCity_id() + "");
                        myApplication.setArea(getItem(position).getArea());
                        myApplication.setArea_id(getItem(position).getArea_id() + "");
                        myApplication.setArea_code(getItem(position).getArea_code() + "");
                        myApplication.setLocation(getItem(position).getLocation());
                        myApplication.setLocation_id(getItem(position).getLocation_id() + "");
                        myApplication.setDetail(getItem(position).getDetail());
                        myApplication.setZip_code(getItem(position).getZip_code());
                        myApplication.setMobile(getItem(position).getMobile());
                        myApplication.setIs_default(getItem(position).getIs_default() + "");

                        startActivityForResult(intent, 2);
                    }

                }
            });

            return convertView;
        }

        private class ViewHolder {
            private LinearLayout ly_confirmation_address;
            private ImageView cb_choose;
            private ImageView img_choose;
            public TextView tv_name;
            public TextView tv_phoneNumber;
            public TextView tv_address;
            public TextView tv_default;
        }
    }

    //获取收货地址列表
    private void GetAddressList() {
        Log.e("url", "1111111==" + 111111111);
        CustomProgressDialog.createDialog(mActivity).show();
        AddressListReq req = new AddressListReq();

        String url = Const.COMMON_ADDRESS + req.urlString();
//        Log.e("ssss", "myApplication.getDataEntity().getUuid()==>" + myApplication.getDataEntity().getUuid());
        req.setUuid(myApplication.getDataEntity().getUuid());
        try {
            String source = req.getString();
            Rsa rsa = new Rsa();
            secret = rsa.encryptByPublic(source);
        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams();
        params.put("token", sharedPreferencesUtil.getAccessToken());
        params.put("secret", secret);
        Async_http_get.get(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Log.e("url", "json==" + response);
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                CustomProgressDialog.Dismiss();
                if (errno.equals("000")) {
                    AddressListResp resp = GsonImpl.get().toObject(response.toString(), AddressListResp.class);
                    addressInfoList.clear();
                    addressInfoList.addAll(resp.getResult().getData());
                    addressListAdapter.notifyDataSetChanged();
                } else if (errno.equals("001")) {
                    CommonUtil.showToast(mActivity, errmsg);
                    Intent intent = new Intent(mActivity, LoginActivity.class);
                    startActivityForResult(intent, 3);
                    Log.e("url", "errmsg==" + errmsg);
                } else {
                    CommonUtil.showToast(mActivity, errmsg);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });

    }


    //删除收货地址
    private void DeleteReceiptAddress() {
        CustomProgressDialog.createDialog(mActivity).Show();
        idList.clear();
        for (AddressListResp.ResultEntity.DataEntity dataEntity : addressInfoList) {
            if (dataEntity.is_check() == true) {
                idList.add(dataEntity.getId());
            }
        }
        if (idList.size() == 0) {
            CommonUtil.showToast(mActivity, "请至少选择一个地址");
            CustomProgressDialog.Dismiss();
            return;
        }

        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < idList.size(); i++) {
            if (i == idList.size() - 1) {
                buffer.append(idList.get(i));
            } else {
                buffer.append(idList.get(i) + ",");
            }
        }
        DeleteAddressReq req = new DeleteAddressReq();
        req.setId(buffer.toString());
        String url = Const.COMMON_ADDRESS + req.urlString() + buffer.toString();
        req.setUuid(myApplication.getDataEntity().getUuid());

        try {
            String source = req.getString();
            Rsa rsa = new Rsa();
            secret = rsa.encryptByPublic(source);
            Log.e("url", "source==" + source);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.e("ssss", "id==>" + buffer.toString());
        Log.e("ssss", "token==>" + sharedPreferencesUtil.getAccessToken());
        Log.e("ssss", "uuid==>" + req.getUuid());

        Log.e("ssss", "secret==>" + secret);

        params.put("id", buffer.toString());
        params.put("token", sharedPreferencesUtil.getAccessToken());
        params.put("secret", secret);
        AsyncHttpClient client = new AsyncHttpClient();
        client.put(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                Log.e("url", "delete_address_json==" + response);
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                if (errno.equals("000")) {
                    GetAddressList();
                    addressListAdapter.notifyDataSetChanged();
                    tv_edit.setText("编辑");
                    tv_addNewAdreess.setVisibility(View.VISIBLE);
                    tv_delete.setVisibility(View.GONE);
                    is_edit = false;
                } else if (errno.equals("999")) {
                    CommonUtil.showToast(mActivity, errmsg);
                    Intent intent = new Intent(mActivity, LoginActivity.class);
                    startActivityForResult(intent, 1);
                } else {
                    CommonUtil.showToast(mActivity, errmsg);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                Log.e("url", "statusCode==" + statusCode + "  responseString==" + responseString);
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.e("url", "requestCode==" + requestCode);
        Log.e("url", "resultCode==" + resultCode);
        switch (requestCode) {
            case 1:
                if (resultCode == 0) {
                    GetAddressList();
                }
                break;
            case 2:
                if (resultCode == Activity.RESULT_OK) {
                    GetAddressList();
                }
//                Log.e("ssss", "@222");
//                GetAddressList();
                break;
            case 3:
                if (resultCode == Activity.RESULT_OK) {
                    GetAddressList();
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        GetAddressList();
    }


}
